<template>
  <div class="app-container">
    <div v-show="!modifyInfo.visible && !detailInfo.visible">
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <NewPageFilter
          ref="pageFilter"
          v-model:query="filterInfo.query.queryMap"
          :query-more-json="true"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :clear-type="clearType"
          :slip-select-request="slipSelectRequest"
        >
        </NewPageFilter>
      </div>

      <div class="filter-wrapper">
        <NewPageFilter :filter-btn="filterInfo.btnList"> </NewPageFilter>
        <div class="display-flex">
          <Group-select
            :options="groupSelectInfo.options"
            v-model:selections="groupSelectInfo.selections"
            @callback="groupSelect"
            @callbackVal="updateGroupSelections"
          ></Group-select>
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <table-container
        v-if="groupFlag"
        class="groupFlag-container"
        :is-group-search="true"
        v-model:data="groupSelectInfo.data"
        :field-list="tableInfo.fieldList"
        :check-box="false"
        :tab-index="false"
        :pager="false"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        :span-method="arraySpanMethod"
        :row-class-name="tableRowClassName"
        @exChange="exChange"
        @sortChange="sortChange"
        @handleEvent="handleEvent"
      >
      </table-container>
      <!-- 表格 -->
      <table-container
        v-else
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :tab-index="false"
        :check-box="false"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        :row-class-name="tableRowOtherClassName"
        @pageInfo="pageInfo"
        @handleEvent="handleEvent"
      >
        <template v-slot:col-orderNo="scope">
          <span class="slip-edit" @click="showDetail(scope.row)">{{
            scope.row.orderNo
          }}</span>
        </template>
      </table-container>
    </div>
    <!-- 新增或修改 -->
    <modify
      v-if="modifyInfo.visible"
      :id="modifyInfo.id"
      v-model:visible="modifyInfo.visible"
      :title="modifyInfo.title"
      :type="modifyInfo.type"
      :current-accounting-interval="modifyInfo.currentAccountingInterval"
      @returnModify="returnModify"
    />

    <!-- 详情页 -->
    <detail
      v-if="detailInfo.visible"
      :id="detailInfo.id"
      v-model:visible="detailInfo.visible"
      :title="detailInfo.title"
      @returnBack="getList"
    />

    <set-preference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :search-list="filterInfo.searchList"
      :field-list="tableInfo.fieldList"
      :customize-user-v-o="filterInfo.query.customizeUserVO"
      @callback="setPreferenceCallback"
    />
    <advanced-search
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      :field-list="tableInfo.fieldList"
      v-model:form-data="advancedSearchInfo.data"
      @callback="advancedSearchCallback"
    />
  </div>
</template>

<script setup name="adverseEventReporting">
import {
  getAdverseEventCustomizePage,
  getAdverseEventCustomizeGroups,
  getAdverseEventAll,
  submitAdverseEvent,
  removeAdverseEvent,
  approveAdverseEvent,
  rejectAdverseEvent,
  refuseAdverseEvent,
  recallAdverseEvent,
  salesReviewAdverseEvent,
} from '@/api/quality.js'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
import { getBusinessKeyById } from '@/api/flowable'
const modify = defineAsyncComponent(() =>
  import('@/views/quality/adverseEvent/modify')
)
const detail = defineAsyncComponent(() =>
  import('@/views/quality/adverseEvent/details')
)
import { ElMessage } from 'element-plus'
import { getDeptAll } from '@/api/core'

const { proxy } = getCurrentInstance()
const emit = defineEmits()

// 过滤相关配置
const groupSelectInfo = reactive({
  options: [],
  selections: [],
  data: [],
})
const filterInfo = reactive({
  sortArr: [],
  copyQueryMap: {},
  query: {
    sortString: '',
    queryMap: {},
    groupMap: {},
    groups: [],
    queryParams: {},
    customizeUserVO: {},
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '高级查询', event: advancedSearchShow },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    {
      type: 'button',
      label: '新增',
      event: create,
      show: proxy.$permission('adverseEvent:add'),
    },
  ],
})

const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  selections: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      {
        label: '修改',
        event: update,
        show: proxy.$permission('adverseEvent:update'),
        ifRender: function (row) {
          return row.status === 1 || row.status === 5
        },
      },
      {
        label: '提交',
        event: submit,
        show: proxy.$permission('adverseEvent:submit'),
        ifRender: function (row) {
          return row.status === 1 || row.status === 5
        },
      },
      {
        label: '删除',
        event: remove,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: proxy.$permission('adverseEvent:delete'),
        ifRender: function (row) {
          return row.status === 1 || row.status === 5
        },
      },
      {
        label: '批准',
        event: (row) => btnFlow(row, 'approve'),
        show: proxy.$permission('adverseEvent:approve'),
        ifRender: checkIfRenderBtnFlow,
      },
      {
        label: '驳回',
        event: (row) => btnFlow(row, 'reject'),
        show: proxy.$permission('adverseEvent:reject'),
        ifRender: checkIfRenderBtnFlow,
      },
      {
        label: '拒绝',
        event: (row) => btnFlow(row, 'refuse'),
        show: proxy.$permission('adverseEvent:refuse'),
        ifRender: checkIfRenderBtnFlow,
      },
      {
        label: '撤回',
        event: recall,
        show: proxy.$permission('adverseEvent:recall'),
        ifRender: checkIfRenderRecall,
      },
      {
        label: '销审',
        event: salesReview,
        show: proxy.$permission('adverseEvent:salesReview'),
        ifRender: checkIfRenderSalesReview,
      },
    ],
  },
})
//明细相关
const detailInfo = reactive({
  visible: false,
  title: '不良事件明细',
  id: '',
})
//新增或更新相关
const modifyInfo = reactive({
  visible: false,
  title: '',
  id: '',
})
const preferenceInfo = reactive({
  visible: false,
})

const advancedSearchInfo = reactive({
  visible: false,
  data: {},
})
let page = reactive({
  page: true,
  curPage: 1, // 当前页
  pageSize: 20, // 每页条数
})

const groupFlag = ref(false)
const clearType = ref(true)
const slipSelectRequest = ref(true)

watch(
  () => proxy.$router.currentRoute.value.name,
  (to, from) => {
    if (!from) return
    if (
      from.includes('myPendingDetail') ||
      from.includes('myFinishedDetail') ||
      from.includes('myApplyDetail')
    ) {
      getList()
    }
  },
  {
    deep: true,
  }
)

onMounted(() => {
  setData()
})

function setData() {
  let obj = {
    statusValue: {
      label: '状态',
      value: 'statusValue',
      asValue: 'status',
      componentType: 'select-model',
      code: 'adverse_event_status',
      show: false,
      hidden: true,
    },
    createUserName: {
      label: '报告人',
      value: 'createUserName',
      asValue: 'createUser',
      componentType: 'select-user',
      minWidth: '200px',
      highlightRow: true,
      checkBox: false,
      show: false,
      hidden: true,
    },
    createDeptName: {
      label: '报告部门',
      value: 'createDeptName',
      asValue: 'createDept',
      query: {
        deptAuth: 'id',
        status: 1,
      },
      api: getDeptAll,
      componentType: 'slip-select',
      show: false,
      hidden: true,
    },
    createTime: {
      label: '报告时间',
      value: 'createTime',
      componentType: 'dateTime',
      minWidth: '200px',
      show: false,
      hidden: true,
    },
    deviceName: {
      label: '设备名称',
      value: 'deviceName',
      minWidth: '200px',
      componentType: 'input',
      type: 'column',
      hidden: true,
    },
    deviceCode: {
      label: '设备编码',
      value: 'deviceCode',
      minWidth: '200px',
      componentType: 'input',
      type: 'column',
      hidden: true,
    },
    rejectReason: {
      label: '驳回原因',
      value: 'rejectReason',
      minWidth: '200px',
      componentType: 'input',
      type: 'column',
      hidden: true,
    },
    productName: {
      label: '产品名称',
      value: 'productName',
      componentType: 'input',
      show: false,
      hidden: true,
    },
  }
  tableInfo.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  filterInfo.searchList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  getCustomize()
}
// 批准/驳回/拒绝
function checkIfRenderBtnFlow(row) {
  return (
    proxy.$store.state.permission.systemConfig
      .allow_asset_adverse_event_approval == 1 && row.status === 2
  )
}
// 销审
function checkIfRenderSalesReview(row) {
  return (
    row.status === 3 &&
    proxy.$store.state.permission.systemConfig
      .allow_asset_adverse_event_approval != 0
  )
}
// 撤回
function checkIfRenderRecall(row) {
  return (
    row.status === 2 ||
    (row.status === 3 &&
      proxy.$store.state.permission.systemConfig
        .allow_asset_adverse_event_approval == 0)
  )
}
function pageInfo(obj) {
  page = obj
}
function showDetail(row) {
  getBusinessKeyById({
    businessKey: row.orderNo,
    businessType: 'adverseEvent',
  }).then((res) => {
    if (res.success) {
      sessionStorage.setItem('storeRowId', row.id)
      if (res.data?.processInstanceId) {
        proxy.$fn.setFlowData(res.data, '', proxy.$route)
      } else {
        detailInfo.visible = true
        detailInfo.title = '资产详情'
        detailInfo.id = row.id
      }
    }
  })
}
function tableRowOtherClassName({ row }) {
  let rowId = sessionStorage.getItem('storeRowId')
  if (rowId && row.id === Number(rowId)) {
    return 'check-row'
  }
  return ''
}
function returnModify() {
  if (modifyInfo.id) {
    getList()
  } else {
    search()
  }
}
//提交
function submit(row = undefined) {
  let ids = []
  if (row) {
    ids = [row.id]
  } else {
    ids = tableInfo.selections.map((item) => item.id)
  }
  let data = {
    flowTaskCommentDto: { approvalType: 'submit' },
    processDefinitionKey: 'adverseEvent',
    orderIds: ids,
  }
  submitAdverseEvent(data).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
//删除
function remove(row) {
  const data = []
  data.push(row.id)
  removeAdverseEvent(data).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
// 审批/拒绝/驳回按钮审批原因弹窗
function btnFlow(row, code) {
  const currentBtnFlow = {
    title: '',
    api: null,
  }
  if (code === 'approve') {
    currentBtnFlow.api = approveAdverseEvent
    const data = {
      orderId: row.id,
    }
    currentBtnFlow.api(data).then((resp) => {
      if (resp && resp.success) {
        getList()
      }
    })
    return
  } else if (code === 'reject') {
    currentBtnFlow.title = '驳回'
    currentBtnFlow.api = rejectAdverseEvent
  } else if (code === 'refuse') {
    currentBtnFlow.title = '拒绝'
    currentBtnFlow.api = refuseAdverseEvent
  }
  proxy
    .$prompt('请输入' + currentBtnFlow.title + '理由', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputValidator: proxy.$fn.maxString200,
      inputErrorMessage: currentBtnFlow.title + '理由不能超过200字符',
    })
    .then(({ value }) => {
      const data = {
        orderId: row.id,
        checkOpt: value,
      }
      currentBtnFlow.api(data).then((resp) => {
        if (resp && resp.success) {
          getList()
        }
      })
    })
}
// 撤回
function recall(row) {
  let ids = []
  if (row) {
    ids.push(row.id)
  } else {
    ids = tableInfo.selections.map((item) => item.id)
  }
  recallAdverseEvent(ids).then((res) => {
    if (res && res.success) {
      getList()
      ElMessage.success({
        message: '操作成功',
        duration: 3000,
        showClose: true,
      })
    } else {
      ElMessage.error({
        message: res.msg,
        duration: 3000,
        showClose: true,
      })
    }
  })
}
// 销审
function salesReview(row) {
  let ids = []
  if (row) {
    ids.push(row.id)
  } else {
    ids = tableInfo.selections.map((item) => item.id)
  }
  salesReviewAdverseEvent(ids).then((res) => {
    if (res && res.success) {
      getList()
      ElMessage.success({
        message: '操作成功',
        duration: 3000,
        showClose: true,
      })
    } else {
      ElMessage.error({
        message: res.msg,
        duration: 3000,
        showClose: true,
      })
    }
  })
}
// 创建
function create() {
  modifyInfo.type = 'create'
  modifyInfo.visible = true
  modifyInfo.title = '新增不良事件'
  modifyInfo.id = null
}
function update(row) {
  getBusinessKeyById({
    businessKey: row.orderNo,
    businessType: 'adverseEvent',
  }).then((res) => {
    if (res.success) {
      sessionStorage.setItem('storeRowId', row.id)
      if (res.data?.processInstanceId) {
        proxy.$fn.setFlowData(res.data, '', proxy.$route)
      } else {
        //修改
        modifyInfo.type = 'update'
        modifyInfo.id = row.id
        modifyInfo.visible = true
        modifyInfo.title = '修改不良事件'
      }
    }
  })
}
function updateGroupSelections(arr) {
  filterInfo.query.groups = arr
  groupSelectInfo.selections = arr
  if (!arr.length) {
    filterInfo.query.groups = []
    filterInfo.query.groupMap = {}
    groupSelectInfo.data = []
    groupFlag.value = false
  }
}
function groupSelect(arr) {
  if (arr.length) {
    //点击分组
    groupFlag.value = true
    filterInfo.query.groups = arr
    groupSelectInfo.selections = arr
    getCustomizeGroupsList()
  } else {
    ElMessage.warning({
      message: '请选择分组条件！',
      showClose: true,
      duration: 3000,
    })
  }
}
async function getCustomizeGroupsList(len, param, expande) {
  //分组查询
  let params = {}
  if (len) {
    params = param
  } else {
    params = filterInfo.query
  }
  if (filterInfo.query.queryDtoList && filterInfo.query.queryDtoList.length) {
    params = proxy.$fn.deepClone(params)
    params.queryMap = {}
  }
  await getAdverseEventCustomizeGroups(params).then(async (res) => {
    if (res && res.success) {
      let data = res.data
      let newData = []
      if (len) {
        await data.forEach((item, index) => {
          newData.push({
            ...item,
            id: index + Math.random(),
            isColspan: true,
            children: [{ ...item, id: index + Math.random(), isColspan: true }],
          })
        })
        expande.children = newData
      } else {
        await data.forEach((item, index) => {
          newData.push({
            ...item,
            id: index + Math.random(),
            isColspan: true,
            children: [{ id: index + Math.random(), isColspan: true }],
          })
        })
        groupSelectInfo.data = newData
      }
    }
  })
}
function exChange(data, expandedRows) {
  //展开分组
  if (expandedRows) {
    let len = data.nextGroups.length
    if (len) {
      let params = {
        ...filterInfo.query,
        groups: data.nextGroups,
        groupMap: { ...data.query },
        queryMap: { ...filterInfo.query.queryMap, ...data.query },
      }
      getCustomizeGroupsList(len, params, data)
    } else {
      let params = {
        ...filterInfo.query,
        groups: [],
        groupMap: {},
        queryMap: { ...filterInfo.query.queryMap, ...data.query },
      }
      getAdverseEventAll(params).then(async (res) => {
        if (res && res.success) {
          let resData = res.data
          await resData.forEach((item, index) => {
            item.id = index + Math.random()
            item.isColspan = false
          })
          data.children = resData
        }
      })
    }
  } else {
    data.children = [{ id: Math.random(), isColspan: true }]
  }
}

function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}
function advancedSearchShow() {
  advancedSearchInfo.visible = true
}
async function advancedSearchCallback(obj) {
  filterInfo.query.queryMap = {}
  let arr = [
    {
      asTbName: 'core_asset',
      columnName: 'use_dept_id',
      queryType: 'IN',
      queryCategory: 'AND',
      value: 'deptAuth',
    },
  ]
  filterInfo.query.queryDtoList = [...obj.queryDtoList, ...arr]
  advancedSearchInfo.data = obj.data
  if (groupSelectInfo.selections.length > 0) {
    await getCustomizeGroupsList()
  } else {
    groupSelectInfo.data = []
    await getList()
  }
  filterInfo.query.queryMap = proxy.$fn.deepClone(filterInfo.copyQueryMap)
  clearType.value = !clearType.value
}
async function getList() {
  tableInfo.refresh = Math.random()
}
function search() {
  advancedSearchInfo.data = {}
  filterInfo.query.queryDtoList = []
  if (groupSelectInfo.selections.length > 0) {
    getCustomizeGroupsList()
  } else {
    groupSelectInfo.data = []
    tableInfo.initCurpage = Math.random()
    tableInfo.refresh = Math.random()
  }
}
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.selections = [...data]
      break
  }
}
function clearSearch() {
  clearType.value = !clearType.value
  filterInfo.query.queryMap = proxy.$fn.deepClone(filterInfo.copyQueryMap)
  search()
}
function getCustomize(_slipSelectRequest = true) {
  let param = {
    tableKey:
      'adverseEventReportingList-com.slip.spd.entity.vo.quality.AdverseEventReportingVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.query.customizeUserVO = data
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.searchList,
        data.detail
      )
      let tableFieldInfo = proxy.$fn.setFieldList(
        tableInfo.fieldList,
        data.detail,
        true
      )

      tableInfo.fieldList = tableFieldInfo.fieldList
      groupSelectInfo.options = tableFieldInfo.groupOption
      filterInfo.query.queryMap = {
        ...searchInfo.queryMap,
        ...filterInfo.query.queryMap,
      }
      filterInfo.copyQueryMap = proxy.$fn.deepClone(filterInfo.query.queryMap)
      filterInfo.searchList = searchInfo.searchList
      filterInfo.searchList.forEach((item) => {
        item.event = search
      })
      slipSelectRequest.value = _slipSelectRequest
      tableInfo.api = getAdverseEventCustomizePage
      getList()
    }
  })
}
function sortChange(column) {
  if (filterInfo.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, filterInfo.sortArr)
    filterInfo.sortArr = arr
    filterInfo.query.sortString = arr.toString()
    getList()
  }
}
function tableRowClassName(row) {
  if (row.row.nextGroups) {
    return 'bg-color-EBEEF5'
  } else {
    return ''
  }
}
function arraySpanMethod({ row, columnIndex }) {
  if (row.nextGroups) {
    if (columnIndex === 0) {
      return {
        rowspan: 1,
        colspan: tableInfo.fieldList.length,
      }
    }
  }
}
</script>

<style scoped></style>
